package com.boxing.servlet;

import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;


public abstract class BaseServlet  extends HttpServlet {
    protected Gson gson;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        gson = new Gson();
        // 在这里收到所有的请求，根据不同的url 进行分发，分发的不同的类或者方法中
//        switch (req.getRequestURI()){
//            case "/webDemo/servlet/login":
//                userInfoServlet.login(req, resp);
//                break;
//            case "/webDemo/servlet/register":
//                userInfoServlet.register(req, resp);
//                break;
//            case "/webDemo/servlet/setIcon":
//                userInfoServlet.setIcon(req, resp);
//                break;
//        }

        // 新增接口时，这里的代码不修改
        String requestURI = req.getRequestURI();
        String methodName = requestURI.substring(requestURI.lastIndexOf("/")+1);
        // 用反射技术调用该方法
        try {
            Method declaredMethod = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            declaredMethod.setAccessible(true);
            declaredMethod.invoke(this, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
